package bsserver.response;

import bsserver.Request;
import bsserver.RequestURI;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Response class for handling PUT Requests
 * @author tblackstone
 */
public class PUTResponse extends Response {

    /**
     * Creates a new Response to a PUT request
     * @param r the PUT Request which caused this Response to be generated
     */
    public PUTResponse(Request r) {
        super(r);
    }

    /**
     * Process a PUT Request to determine how to respond to it
     * @param r the Request to process
     * @return an appropriate Response object
     */
    public static Response process(Request r) {

        Response response;

        // Check Resource Permissions
        String validUser = findClientPermissions(r);
        if (validUser == null) {
            Response authRequiredResponse = new ErrorResponse(r, 401);
            authRequiredResponse.setHeader("WWW-Authenticate",
                    "Basic realm=\"" + r.getAuthInfo().getAuthName() + "\"");
            return authRequiredResponse;
        }
        r.setRemoteUser(validUser);


        RequestURI requestURI = r.getRequestURI();

        File newResource = new File(r.getRequestURI().getAbsolutePath());
        FileOutputStream os;


        try {
            os = new FileOutputStream(newResource);
        } catch (FileNotFoundException ex) {
            // Could not create file, it cannot be opened, or it is a directory
            return new ErrorResponse(r, 403);
        }


        try {
            os.write(r.getBody());
        } catch (IOException ex) {
        }

        response = new BodylessResponse(r, 201);
        String locationURL = "http://" + r.getHeader("Host") + r.getRequestURI().getURIString();
        response.setHeader("Location", locationURL);

        return null;
    }
}
